package main

import (
	"time"

	"github.com/gin-gonic/gin"
	"gitee.com/dayu1985/framework/net/web"
	"gitee.com/dayu1985/framework/net/web/jwt"
	"gitee.com/dayu1985/framework/storage/cache/cache_leveldb"
)

func main() {

	router := gin.Default()

	cacher := cache_leveldb.NewLevelCacheOpenFile("levelcache")
	au := jwt.NewGinJWT(30*time.Hour, "HDKJ1234!", cacher)

	public := router.Group("")
	private := router.Group("")

	public.GET("/auth", func(ctx *gin.Context) {

		s, err := au.Sign(map[string]interface{}{})

		if err != nil {
			panic(err)
		}

		ctx.JSON(200, s)
	})

	private.Use(au.Auth(func(ctx *gin.Context, token *jwt.Token) {

		if token != nil {

			ctx.Set("jwt_signature", token.Raw)
		}
	}))

	private.GET("/hello", func(ctx *gin.Context) {

		ctx.String(200, "Hello World!")
	})

	private.GET("/refresh/:token", func(ctx *gin.Context) {

		refresh_token := ctx.Param("token")
		signature, exists := ctx.Get("jwt_signature")

		if exists {

			access_token := signature.(string)
			s, err := au.Refresh(access_token, refresh_token)

			if err != nil {
				web.Bad(ctx, 200, "未授权!")
				return
			}

			ctx.JSON(200, s)
		}
	})

	router.Run()
}
